<?php

namespace plugins\assets\controller;

use app\controller\backend\BaseController;
use plugins\assets\model\AssetsServer;
use plugins\assets\validate\AssetsServerValidate;
use think\exception\ValidateException;

class ServerController extends BaseController
{
    public function index()
    {
        $param = $this->request->only([
            'limit' => 10,
        ]);

        $where = [];

        //获取当前主机的ip
        $ip = $this->getLocalIp();
        $serverModel = new AssetsServer();
        if (!$serverModel->isExist(['public_ip' => $ip])) {
            $serverModel->insert([
                'title' => lang('本系统主机'),
                'public_ip' => $ip,
            ]);
        }

        $listRes = $serverModel->getList($where, ['admin'], $param['limit'], 'id asc');
        $list = pageReturn($listRes);

        return json($list);
    }

    public function add()
    {
        $param = $this->request->post([
            'title' => '',
            'desc' => '',
            'public_ip' => '',
            'service_provider' => '',
            'price' => '',
            'os' => '',
            'buy_date' => '',
            'expire_date' => '',
        ]);

        try {
            validate(AssetsServerValidate::class)->scene('save')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $model = new AssetsServer();
        if ($model->isExist([
            ['public_ip', '=', $param['public_ip']]
        ])) {
            return jsonReturn(-2, lang('公网ip已经存在'));
        }

        if (empty($param['buy_date'])) unset($param['buy_date']);

        if (empty($param['expire_date'])) {
            unset($param['expire_date']);
        } else {
            $day = (strtotime($param['expire_date']) - time()) / (60 * 60 * 24);
            $day = intval($day);
            if ($day > 0) {
                $param['hint'] = lang('还有').$day.lang("天过期");
            } else {
                $day = abs($day);
                $param['hint'] =  lang('主机已过期').$day.lang("天");
            }
        }
        $param['seller_id'] = $this->admin['seller_id'];


        $res = $model->add($param);

        return json($res);
    }

    public function edit()
    {
        $param = $this->request->post([
            'id' => 0,
            'title' => '',
            'desc' => '',
            'public_ip' => '',
            'service_provider' => '',
            'price' => '',
            'os' => '',
            'buy_date' => '',
            'expire_date' => '',
        ]);
        try {
            validate(AssetsServerValidate::class)->scene('update')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $model = new AssetsServer();
        if ($model->isExist([
            ['id', '<>', $param['id']],
            ['public_ip', '=', $param['public_ip']]
        ])) {
            return jsonReturn(-2, lang('公网ip已经存在'));
        }

        if (empty($param['buy_date'])) unset($param['buy_date']);
        if (empty($param['expire_date'])) {
            unset($param['expire_date']);
        } else {
            $day = (strtotime($param['expire_date']) - time()) / (60 * 60 * 24);
            if ($day > 0) {
                $param['hint'] =  lang('还有').$day.lang("天过期");
            } else {
                $day = abs($day);
                $param['hint'] =  lang('主机已过期').$day.lang("天");
            }
        }

        $model = new AssetsServer();
        $res = $model->edit(['id' => $param['id']], $param);

        return json($res);
    }

    public function del()
    {
        $param = $this->request->post([
            'id' => 0,
        ]);
        try {
            validate(AssetsServerValidate::class)->scene('del')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }

        $model = new AssetsServer();
        $res = $model->where(['id' => $param['id']])->delete();
        if ($res === false) {
            return jsonReturn(-1, lang('删除失败'));
        }
        return jsonReturn(0, lang('删除成功'));
    }

    protected function getLocalIp()
    {
        $result = gethostbynamel(gethostname());
        if ($result === false) {
            return '127.0.0.1';
            throw new \Exception(lang('无法解析出IP'));
        }

        $filterIP = '127.0.0.1';
        $result = array_filter($result, function ($item) use ($filterIP) {
            return $item != $filterIP;
        });

        if (empty($result)) {
            return '127.0.0.1';
            throw new \Exception(lang('无法获取IP'));
        }
        $result = array_values($result);

        return $result[0];
    }
}